﻿#if !Profile && HKTN
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using O1.Kernel.Storage;
using O1.Kernel.Storage.Transactions;

namespace O1.Profiling
{
    class Program
    {
#if !DEBUG
        private const int size = 1024 * 1024;// * 10;
#endif
#if DEBUG
        private const int size = 1;
#endif

        private const int MaxCellSz = 4096;

        private static readonly string connString = ConfigurationManager.ConnectionStrings["O1"].ConnectionString;

        // effect of padding? will spill to the next 16 byte boundary once 8 bytes are exceeded, requires 8 bytes of memory overhead for malloc

        static void Main(string[] args)
        {
            var proc = Process.GetCurrentProcess();
            var bytesAllocated = proc.WorkingSet64;

            Console.Write("Before allocation..." + bytesAllocated);
            Console.ReadLine();

            var stopwatch = Stopwatch.StartNew();

            Console.WriteLine("Allocated " + size + " trunk storage.");
            Console.WriteLine("...in " + stopwatch.ElapsedMilliseconds + " milliseconds.");

            Console.Write("Before cell population...");
            Console.ReadLine();

            stopwatch.Restart();

            // Writing to SQL server is about 1ms per write...OK for logging, but not OLTP
            for(int i = 0; i < size; i++)
            {
               AddCell(i, new byte[Math.Max(i % MaxCellSz, 16)]);
            }

            //for (int i = 0; i < size; i++)
            //{
            //    int version;
            //    var data = ReadCell(i, out version);
            //    data = ReadCell(i, out version);
            //    // data[0] = 255;

            //    // WriteCell(i, new byte[Math.Max(i % MaxCellSz, 16)], version);
            //}

            Console.Write("Allocated, Read and updated " + size + " cells ");
            Console.WriteLine("...in " + stopwatch.ElapsedMilliseconds + " milliseconds.");
            Console.ReadLine();
        }

        private static void AddCell(long key, byte[] data)
        {
            using (var connection = new SqlConnection(connString))
            using (var command = new SqlCommand("dbo.add_Cell", connection))
            {
                command.CommandType = CommandType.StoredProcedure;
                command.Parameters.Add("cell_id", SqlDbType.BigInt).Value = key;
                command.Parameters.Add("data", SqlDbType.VarBinary).Value = data;

                connection.Open();
                command.ExecuteNonQuery();
            }
        }
    }
}

#endif